import React, { useState } from 'react';
import { useGame } from '../GameContext';
import { allIngredients } from '../pizzaRecipes';
import { motion } from 'framer-motion';

const IngredientsPanel: React.FC = () => {
  const { state, selectIngredient, resetSelectedIngredients, cookPizza } = useGame();
  const { selectedIngredients, currentOrderId, ovenSlots } = state;
  const [cookingResult, setCookingResult] = useState<'success' | 'error' | null>(null);

  // 检查是否可以烹饪
  const canCook = () => {
    if (!currentOrderId) return false;
    // 检查是否有空的烤炉槽位
    const hasEmptySlot = ovenSlots.some(slot => slot.status === 'empty');
    return hasEmptySlot && selectedIngredients.length > 0;
  };

  // 处理烹饪披萨
  const handleCook = () => {
    const success = cookPizza();
    setCookingResult(success ? 'success' : 'error');
    
    // 2秒后清除结果提示
    setTimeout(() => {
      setCookingResult(null);
    }, 2000);
  };

  // 获取材料的图标
  const getIngredientIcon = (ingredient: string): string => {
    const iconMap: Record<string, string> = {
      'Dough': '🍞',
      'Tomato Sauce': '🍅',
      'Mozzarella': '🧀',
      'Pepperoni': '🥓',
      'Mushrooms': '🍄',
      'Bell Peppers': '🫑',
      'Sausage': '🌭',
      'Bacon': '🥓'
    };
    return iconMap[ingredient] || '🥫';
  };

  // 检查是否有当前选中的订单
  const hasSelectedOrder = !!currentOrderId;

  return (
    <div className="game-card">
      <h2 className="text-2xl font-bold text-amber-800 mb-4">材料面板</h2>
      
      {!hasSelectedOrder && (
        <motion.div 
          className="p-4 bg-yellow-100 rounded-lg mb-4 text-center"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <p className="text-yellow-700">请先从订单队列中选择一个订单</p>
        </motion.div>
      )}

      {/* 已选材料区域 */}
      {hasSelectedOrder && (
        <div className="mb-4">
          <h3 className="text-lg font-semibold mb-2">已选材料:</h3>
          <div className="flex flex-wrap gap-2">
            {selectedIngredients.length === 0 ? (
              <p className="text-gray-500">未选择任何材料</p>
            ) : (
              selectedIngredients.map((ingredient, index) => (
                <motion.div
                  key={index}
                  className="flex items-center bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm"
                  initial={{ scale: 0.8, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  exit={{ scale: 0.8, opacity: 0 }}
                  transition={{ duration: 0.2 }}
                >
                  <span className="mr-1">{getIngredientIcon(ingredient)}</span>
                  {ingredient}
                </motion.div>
              ))
            )}
          </div>
          
          {selectedIngredients.length > 0 && (
            <button 
              className="mt-2 text-sm text-blue-600 hover:underline"
              onClick={resetSelectedIngredients}
            >
              清空选择
            </button>
          )}
        </div>
      )}

      {/* 可用材料区域 */}
      {hasSelectedOrder && (
        <div>
          <h3 className="text-lg font-semibold mb-2">可用材料:</h3>
          <div className="flex flex-wrap">
            {allIngredients.map((ingredient) => {
              const isSelected = selectedIngredients.includes(ingredient);
              
              return (
                <motion.button
                  key={ingredient}
                  className={`ingredient-button ${isSelected ? 'selected' : ''}`}
                  onClick={() => selectIngredient(ingredient)}
                  disabled={isSelected}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                >
                  <span className="mr-1">{getIngredientIcon(ingredient)}</span>
                  {ingredient}
                </motion.button>
              );
            })}
          </div>
        </div>
      )}

      {/* 烹饪按钮 */}
      {hasSelectedOrder && (
        <div className="mt-6">
          <motion.button
            className={`game-button ${canCook() ? 'success' : 'bg-gray-400'}`}
            onClick={handleCook}
            disabled={!canCook()}
            whileHover={canCook() ? { scale: 1.05 } : {}}
            whileTap={canCook() ? { scale: 0.95 } : {}}
          >
            放入烤炉
          </motion.button>
        </div>
      )}

      {/* 烹饪结果提示 */}
      {cookingResult === 'success' && (
        <motion.div
          className="mt-4 p-3 bg-green-100 text-green-800 rounded-lg text-center"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -20 }}
          transition={{ duration: 0.3 }}
        >
          <p>披萨开始烘烤！</p>
        </motion.div>
      )}

      {cookingResult === 'error' && (
        <motion.div
          className="mt-4 p-3 bg-red-100 text-red-800 rounded-lg text-center"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -20 }}
          transition={{ duration: 0.3 }}
        >
          <p>材料必须与配方完全一致，不能多也不能少！</p>
        </motion.div>
      )}
    </div>
  );
};

export default IngredientsPanel;